<?php

require_once("./Model/LoginModel.php");
require_once("./Model/User.php");
require_once("./Model/UserList.php");
require_once("./View/NavigationView.php");
require_once("./View/LoginView.php");

class LoginController {
	
	/**
	 * @var NavigationView
	 */
	private $navigationView;
	
	 /**
	 * @var LoginView
	 */
	private $loginView;
	
	/**
	 * @var LoginModel
	 */
	private $loginModel;
	
	/**
	 * 
	 * @var UserList
	 */
	private $userList;
	
	/**
	 * @var NavigationView 	$navigationView
	 * @var LoginModel		$loginModel
	 * @var LoginView		$loginView
	 */
	public function __construct() {
		$this->navigationView = new NavigationView();
		$this->loginModel = new LoginModel();
		$this->loginView = new LoginView($this->navigationView);
										 
		$this->userList = new UserList();
	}
	
	public function runLoginApp() {
		if ($this->navigationView->userWantsToLogin() && 
			!$this->loginModel->userIsLoggedIn()) {
				
			$this->loginUser();
		}
		else if ($this->navigationView->userWantsToLogout() && 
				 $this->loginModel->userIsLoggedIn()) {
				 	
			$this->logoutUser();
		}
		
		if ($this->loginModel->userIsLoggedIn() && $this->loginModel->checkLoginSession()) {
			return $this->loginView->getLogoutHTML($this->loginModel->getUsername());
		}
		else {
			return $this->loginView->getLoginHTML();
		}
	}
	
	public function createTempUserFromClient($password) {
		
	}
	
	public function loginUser() {
		if ($this->loginView->isCookiesSet() || $this->loginView->isInputDataSet()) {
			$isAuthed = false;
			$userFromServer = null;
			$userFromClient = new User($this->loginView->getUsername(),
									   $this->loginView->getPassword(),
									   $this->loginView->isCookiesSet());
		    try{
				$userFromServer = $this->userList->findUser($userFromClient);
			}
			catch (\Exception $e) {}
			if ($userFromServer) {
				$isAuthed = $userFromServer->matchPasswords($userFromClient->getPasswordEncrypted());
				if ($this->loginView->isCookiesSet() && $isAuthed) {
					$isAuthed = $userFromServer->matchExpireDate($userFromClient->getExpireDate());
				}
				if ($isAuthed) {
					$this->loginModel->setLoginSessionLoggedIn($userFromServer->getUsername());
					if ($this->loginView->saveLoginData() || $this->loginView->isCookiesSet()) {
						// Update user on server with new expireDate for cookies.
						$userFromServer->createNewPasswordTemporary();
						$this->userList->update($userFromServer);
						$this->loginView->setLoginDataCookies($userFromServer->getUsername(),
															  $userFromServer->getPasswordTemporary(),
															  $userFromServer->getExpireDate());
					}
				}
			}
			$this->loginView->userAuthed($isAuthed);
		}
	}

	public function logoutUser() {
		$this->loginModel->setLoginSessionLoggedOut();
		$this->loginView->logoutUser();
	}
}